package cn.edu.swu.bc.servlet;

import cn.edu.swu.bc.filter.AuthFilter;
import cn.edu.swu.bc.utils.DBUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;


public class RegisterServlet extends HttpServlet {

    private static final long serialVersionUID = 119822121124340L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            this.doPost(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String username = request.getParameter("user");
        String nickname = request.getParameter("nickname");
        String password = request.getParameter("pass");
        String errorMsg = null;
        if (username.isEmpty() || nickname.isEmpty() || password.isEmpty()) {
            errorMsg = "请正确填入注册信息";
            request.setAttribute("errorMsg", errorMsg);
            request.getRequestDispatcher("./register.jsp").forward(request, response);
        }
        HttpSession session = request.getSession(true);
        String sql = String.format("INSERT INTO `users` values (null,'%s','%s',null,'%s',null,null,null,null) ", username, password, nickname);
        try {
            DBUtils.insert(sql);
            session.setAttribute(AuthFilter.USER_ID, DBUtils.getRigsterUserID());
            session.setAttribute(AuthFilter.USER_NICKNAME, nickname);
            session.setAttribute(AuthFilter.USER_AVATAR, null);
            session.setAttribute(AuthFilter.USER_SIGNATURE, null);
            session.setAttribute(AuthFilter.LOGIN_STATUS, Boolean.TRUE);
            response.sendRedirect("./u/index.html");
        } catch (SQLException throwables) {
            if (throwables.getErrorCode() == 1062) {
                errorMsg = "用户名已被占用，请重新输入";
                request.setAttribute("errorMsg", errorMsg);
            }
            request.setAttribute("errorMsg", errorMsg);
            request.getRequestDispatcher("./register.jsp").forward(request, response);
        }

    }
}
